<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <!-- Tips: 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮 -->
    <form class="form-search"
      action="/">
      <van-search v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow=false" />

    </form>

    <!-- 搜索结果 -->
    <search-result v-if="isResultShow"
      :search-text="searchText"></search-result>
    <!-- 搜索建议 -->
    <search-suggestion v-else-if="searchText"
      :searchText='searchText'
      @search="onSearch"></search-suggestion>
    <!-- 搜索历史 -->
    <search-history :searchHistory="searchHistory"
      @search="onSearch"
      @clear-histories="searchHistory=[]"
      v-else></search-history>

  </div>
</template>

<script>

import SearchHistory from './components/SearchHistory.vue'
import SearchSuggestion from './components/SearchSuggestion.vue'
import SearchResult from './components/SearchResult.vue'
import { getItem, setItem } from '@/utils/index.js'

export default {
  name: 'Search',
  data () {
    return {
      // 搜索内容
      searchText: '',
      isResultShow: false, // 控制搜索结果
      // 存储历史记录
      searchHistory: getItem('serach-histories') || []
    }
  },
  watch: {
    //      数据持久化
    // 利用 watch 监视统一存储数据
    searchHistory (val) {
      setItem('serach-histories', val)
    }
  },
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult

  },
  methods: {
    // 确认搜索时触发
    onSearch (val) {
      console.log(val)
      // 更新文本框内容
      this.searchText = val

      // 存储历史记录
      // 要求：不要有重复的历史纪录最新的排在前面
      const index = this.searchHistory.indexOf(val)
      if (index !== -1) {
        this.searchHistory.splice(index, 1)
      }
      this.searchHistory.push(val)
      // 渲染搜索结果
      this.isResultShow = true

      // this.searchText = ''
    },
    onCancel () {
      // console.log('cannel')
      this.$router.back()
    }
  }
}
</script>

<style lang="less" scoped>
.search-container{
   padding-top: 108px;
  // 搜索
  .form-search{
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
    .van-search__action{
      color: #fff;
    }
  }
}
</style>
